package util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public abstract class WorkDayUtil {
    private static final Logger logger = LoggerFactory.getLogger(WorkDayUtil.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");

    public static void main(String[] args) throws IOException, ParseException {
        Date dateTest = null;
        if (args.length>0 && StringUtils.isNotBlank(args[0])) {
            dateTest = sdf.parse(args[0]);
        }else{
            dateTest = new Date();
        }
        System.out.println(sdf.format(dateTest));
        System.out.println("isWork:" + isWork(dateTest));
    }

    /**
     * 根据key值获取json的array数组数据
     *
     * @param param
     * @param arr
     * @return
     */
    private static JSONArray getArrayParamFromArray(String param, JSONArray arr) {
        JSONArray key = null;
        for (Object datum : arr) {
            String data_Str = datum.toString();
            JSONObject data_Json = (JSONObject) JSONObject.parse(data_Str);
            key = data_Json.getJSONArray(param);
        }
        return key;
    }

    private static Boolean isWeekend(Date bDate) throws ParseException {
        Boolean isWeekends = false;
        Calendar cal = Calendar.getInstance();
        cal.setTime(bDate);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            return true;
        } else {
            return isWeekends;
        }
    }

    public static boolean isWork(Date dateInput) throws IOException, ParseException {
        boolean isHoliday = false;
        boolean isVwork = false;
        boolean isWeekend = false;
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateInput);

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        dateInput = sdf.parse(year + "-" + month + "-" + day);
        String url = "";

        //创建http请求客户端
        CloseableHttpClient build = HttpClientBuilder.create().build();
        //爬虫抓取的百度万年历的接口
        url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=" + year + "%E5%B9%B4" + Integer.valueOf(month) + "%E6%9C%88&resource_id=39043&format=json&tn=wisetpl";
        //发送get请求
        HttpGet httpGet = new HttpGet(url);
        //执行发送Get请求
        CloseableHttpResponse execute = build.execute(httpGet);
        //创建放假list集合存放日期
        List<Date> holidayList = new ArrayList<>();
        //创建补班list集合存放日期
        List<Date> vworkList = new ArrayList<>();

        //判断响应的状态是否为：200
        if (execute.getStatusLine().getStatusCode() == 200) {
            //获取响应的实体
            HttpEntity entity = execute.getEntity();
            System.out.println(entity);
            //设置响应编码格式
            String context = EntityUtils.toString(entity, "utf-8");
            //将字符串转换为json格式
            JSONObject parseContext = (JSONObject) JSONObject.parse(context);
            //获取json数据里的data数组
            JSONArray data = parseContext.getJSONArray("data");
            JSONArray days = getArrayParamFromArray("almanac", data);
            //遍历list
            for (Object o : days) {
                String sql = o.toString();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(sql);
                Date date = sdf.parse(jsonObject.getString("year") + "-" + jsonObject.getString("month") + "-" + jsonObject.getString("day"));
                String status = jsonObject.getString("status");
                if ("1".equals(status)) {
                    holidayList.add(date);
                }
                if ("2".equals(status)) {
                    vworkList.add(date);
                }
            }
            for (int i = 0; i < holidayList.size(); i++) {
                if (holidayList.get(i).equals(dateInput)) {
                    isHoliday = true;
                }
            }
            for (int i = 0; i < vworkList.size(); i++) {
                if (vworkList.get(i).equals(dateInput)) {
                    isVwork = true;
                }
            }
            isWeekend = isWeekend(dateInput);

            if (isHoliday) {
                logger.info("今天是放假");
                return false;
            } else if (isVwork) {
                logger.info("今天是补班日");
                return true;
            } else if (isWeekend) {
                logger.info("今天是周末");
                return false;
            } else {
                return true;
            }
        }
        return true;
    }


}
